package com.xiang.utils;

import com.xiang.config.EsConfig;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * id查询
 *
 * @author xiangtianlei@gogpay.cn
 * @date 2023-01-30
 */
public class IdQuery {
    RestHighLevelClient client = EsConfig.getClient();
    Logger logger = LoggerFactory.getLogger(IdQuery.class);

    /**
     * 通过id查询
     */
    @Test
    public void findById() throws IOException {
        // 创建getRequest
        GetRequest request = new GetRequest(EsConfig.INDEX_NAME, "19ada928cb6c474d801fb765742d2403");
        // 执行请求
        GetResponse res = client.get(request, RequestOptions.DEFAULT);
        logger.info("输出结果：{}", res.getSourceAsMap());
    }

    /**
     * 根据多个id进行查询
     */
    @Test
    public void findByIds() throws IOException {
        // 创建查询request
        SearchRequest request = new SearchRequest(EsConfig.INDEX_NAME);
        // 封装查询语句
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.idsQuery().addIds("6d3354d9a67546f4bfb813b1b178d665", "517fafb7d2414f9b892d2bcbcc040f51"));
        request.source(builder);
        //  执行查询
        SearchResponse res = client.search(request, RequestOptions.DEFAULT);
        logger.info("查询语句:{}", request.source().toString());
        for (SearchHit hit : res.getHits().getHits()) {
            logger.info("输出结果为:{}", hit.getSourceAsMap());
        }

    }
}
